package com.zg.common.core.validation;

import cn.hutool.core.util.StrUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则校验
 * @author Zxb
 */
@Documented
@Constraint(validatedBy = {Regex.Validator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Regex {

    String message() default "不符合要求的数据格式";
    String rule() default "";

    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};


    class Validator implements ConstraintValidator<Regex, String> {
        private String ruleStr = "";
        @Override
        public void initialize(Regex constraintAnnotation) {
            ruleStr = constraintAnnotation.rule();
        }
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if(StrUtil.isBlank(ruleStr)){
                return true;
            }
            if (StrUtil.isEmpty(value)) {
                return true;
            }
            Pattern pattern = Pattern.compile(ruleStr);
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        }
    }
}
